package com.craftworks.driver.bluetop;

import com.craftworks.mpeg2.transmission.IODevice;
import com.craftworks.mpeg2.transmission.IODeviceDriver;
import com.craftworks.mpeg2.transmission.IODeviceManager;
import java.io.IOException;
import java.net.URI;

public final class BSTC12V5Driver implements IODeviceDriver
{
    static
    {
        try
        {
            IODeviceManager.registerDeviceDriver(new BSTC12V5Driver());
            System.out.println("BSTC12V5Driver successfully registered.");
        } catch (IOException ex)
        {
            System.err.println("fail to register BSTC12V5Driver.");
            ex.printStackTrace(System.err);
        }
    }

    @Override
    public String name()
    {
        return "BSTC12V5Driver";
    }

    @Override
    public String vendor()
    {
        return "CraftWorks Inc.";
    }

    @Override
    public String version()
    {
        return "1.0";
    }

    @Override
    public String description()
    {
        return "bridge driver for bluetop bstc-12(v5) card.";
    }

    @Override
    public String[] scan()
    {
        int count = (int) BSTC12V5Adapter.devcnt();
        String[] uris = new String[count];
        if (count == 1)
        {
            uris[0] = "bluetop://bstc12";
        } else
        {
            for (int i = 0; i < count; i ++)
                uris[i] = "bluetop://bstc12:" + i;
        }
        return uris;
    }

    @Override
    public IODevice open(String uri) throws IOException
    {
        // URI: <scheme>://<card_type>:<device_id>
        // scheme: "bluetop"
        // card_type: "bstc12"
        // device_id: [0, 7]
        // Example: bluetop://bstc12:1
        // Special: bluetop://bstc12:0 => bluetop://bstc12
        if (!accepts(uri))
            return null;

        int port = URI.create(uri).getPort();
        if (port == -1)
            port = 0;
        return new BSTC12V5(port);
    }

    @Override
    public boolean accepts(String uri)
    {
        URI target = URI.create(uri);
        String scheme = target.getScheme().toLowerCase();
        String host = target.getHost().toLowerCase();
        int port = target.getPort();
        if (port == -1)
            port = 0;

        return (scheme.equals("bluetop") &&
                host.equals("bstc12") &&
                BSTC12V5Adapter.isAcceptableDeviceID(port));
    }
}
